const enterpriseVue = new Vue({
    el: '#app',
    data() {
        return {
            rules: {
                Start_Date: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
                End_Date: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
                // ShopColumn_Id: [{ required: true, message: '请选择栏目', trigger: 'blur' }],
            },
            Article_SerialNumber: [{ required: true, message: '请选择商品', trigger: 'change' }],
            Specifications_Name: [{ required: true, message: '请选择规格', trigger: 'change' }],
            Distribute: [{ required: true, message: '请输入分配数量', trigger: 'blur' }],
            Integral_Unit_Price: [{ required: true, message: '请输入销售单价', trigger: 'blur' }],
            store: [],
            column: [],
            shop: [],
            specs: [],
            isDisabled: true,
            type: '', 
            //导入属性
            fileList: [],
            integral_unitprice: [],
            Store_SerialNumber: [],
            Start_Date: '',
            End_Date: '',
            Distribute: '',
            Enterprise: [],
            dialogVisible: false,
            always: '00:00:00',
            form: {     //销售价格单
                Integral_Unit_Price_SerialNumber: "",
                Start_Date: '',
                End_Date: '',
                Column_Type: '',
                Row_Status: '2',
                // integral_unitprice_storescope
                // integral_unitprice_storescope
                Enterprise_Info_SerialNumber: $.cookie("enterprise"),
                Children: {
                    integral_unitprice_detail: [{     //销售价格单明细
                        Integral_Unit_Price_Detail_SerialNumber: "",
                        Integral_Unit_Price_SerialNumber: '',
                        Article_Specifications_SerialNumber: '',
                        Article_SerialNumber: '',
                        Unit_Price: '',
                        Integral_Unit_Price: '',
                        Sign: '无货货主',
                        Distribute: '',
                        specs: [],
                        Children: {
                            integral_unitprice_stock: []
                        }
                    }],
                    integral_unitprice_storescope: [{     //销售价格单适用店铺
                        Integral_Unit_Price_StoreScope_SerialNumber: "",
                        Integral_Unit_Price_SerialNumber: '',
                        Store_SerialNumber: '',
                    }],
                    integral_unitprice_column: [{
                        Integral_Unit_Price_Column_SerialNumber: '',
                        Integral_Unit_Price_SerialNumber: '', //单价流水号
                        ShopColumn_Id: '',  //栏目流水号
                        Column_Type: '', //栏目属性
                    }]
                }
            },
            loading: false,
            Enterprise_Info_SerialNumber: $.cookie("enterprise")
        }
    },
    mounted() {
        const Integral_Unit_Price_SerialNumber = sessionStorage.getItem("Integral_Unit_Price_SerialNumber")
        // this.getData(Integral_Unit_Price_SerialNumber)
        // console.log(Integral_Unit_Price_SerialNumber)
        this.getSubtableInquiryOriginal(Integral_Unit_Price_SerialNumber)
    },
    computed: {
        formatTime() {
            return function (time) {
                let d = new Date(time);
                let year = d.getFullYear();
                let month = d.getMonth() + 1
                let day = d.getDate()
                let hour = d.getHours()
                let minute = d.getMinutes()
                let second = d.getSeconds()
                if (month < 10) { month = '0' + month }
                if (day < 10) { day = '0' + day }
                if (hour < 10) { hour = '0' + hour }
                if (minute < 10) { minute = '0' + minute }
                if (second < 10) { second = '0' + second }
                return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
            };
        },
    },
    methods: {
        // 查询原值
        getSubtableInquiryOriginal(Primary_Key){
            const _this=this
           console.log('获取原值')
            $.ajax({
                type: 'POST',
                url: DomainName + `/getSubtableInquiryOriginal?token=${$.cookie('token')}`,
                data: { 
                 Primary_Key,
                 JSONObject:JSON.stringify({
                    integral_unitprice:{
                        integral_unitprice_column:{},
                        integral_unitprice_detail:{
                            integral_unitprice_stock:{} 
                        },
                        integral_unitprice_storescope:{}  
                    }
                })
                },
                success: function (res) {
                  console.log('获取原值',res)
                  _this.form=res.integral_unitprice[0]
                },
                complete: function (XMLHttpRequest) {
                  _this.loading = false
                  if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                    window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                  }
                },
                dataType: "json"
              });
        },
        getData(Integral_Unit_Price_SerialNumber) {
            const _this = this
            $.ajax({
                url: DomainName + '/SalesUnitprice_Edit',
                type: 'POST',
                data: { Data: Integral_Unit_Price_SerialNumber, token: $.cookie("token") },
                success: function (res) {
                    console.log(res);
                    // _this.form = res.integral_unitprice[0]
                    _this.form.Children.integral_unitprice_detail.forEach(item => {
                        item['Distribute'] = '100'
                        item['Children'] = {
                            integral_unitprice_stock: []
                        }
                    })
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
            $.ajax({
                type: 'POST',
                url: DomainName + "/getInquiryAction",
                data: {
                    Data: "store_info",
                    token: $.cookie("token")
                },
                success: function (res) {
                    res = res.filter(function (item) {
                        return item.Row_Status != '1'
                    })
                    for (let i = 0; i < res.length; i++) {
                        _this.store.push(res[i]);
                    }
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                dataType: "json"
            });

            $.ajax({
                url: DomainName + '/ColumnAll',
                type: 'POST',
                data: { token: $.cookie("token") },
                success: function (res) {
                    console.log(res)
                    res = res.filter(function (item) {
                        return item.Row_Status != '1'
                    })
                    for (let i = 0; i < res.length; i++) {
                        _this.column.push(res[i]);
                    }
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
            // 获取商品
            $.ajax({
                url: DomainName + '/getArticleInfo2Action',
                type: 'POST',
                data: { token: $.cookie("token") },
                success: function (res) {
                    console.log(res)
                    res = res.filter(function (item) {
                        return item.Row_Status == '0'
                    })
                    res.forEach(item => {
                        item.Article_Name = item.Article_Name + '(所属企业:' + item.Enterprise_Name + ')'
                    })
                    for (let i = 0; i < res.length; i++) {
                        _this.shop.push(res[i]);
                    }
                },
                complete: function (XMLHttpRequest) {
                    _this.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
        },
        add_integral_unitprice_storescope() {
            this.form.Children.integral_unitprice_storescope.push({     //销售价格单适用店铺
                Sales_Unit_Price_StoreScope_SerialNumber: "",
                Integral_Unit_Price_SerialNumber: this.form.Integral_Unit_Price_SerialNumber,
                Store_SerialNumber: '',
            })
        },
        remove_integral_unitprice_storescope() {
            if (this.form.Children.integral_unitprice_storescope.length > 1) {
                this.form.Children.integral_unitprice_storescope.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        add_integral_unitprice_column() {
            console.log(this.form.Children)
            this.form.Children.integral_unitprice_column.push({  //栏目
                Sales_Unit_Price_Column_SerialNumber: '',
                Integral_Unit_Price_SerialNumber: this.form.Integral_Unit_Price_SerialNumber, //单价流水号
                ShopColumn_Id: '',  //栏目流水号
                Column_Type: '', //栏目属性
            })
        },
        remove_integral_unitprice_column() {
            if (this.form.Children.integral_unitprice_column.length > 1) {
                this.form.Children.integral_unitprice_column.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        add_integral_unitprice_detail() {
            this.form.Children.integral_unitprice_detail.push({     //销售价格单明细
                Sales_Unit_Price_Detail_SerialNumber: "",
                Integral_Unit_Price_SerialNumber: this.form.Integral_Unit_Price_SerialNumber,
                Article_SerialNumber: '',
                Article_Specifications_SerialNumber: '',
                Unit_Price: '',
                Sales_Unit_Price: '',
                Sign: '无货货主',
                Distribute: '',
                specs: [],
                Children: {
                    integral_unitprice_stock: []
                }
            })
        },
        remove_integral_unitprice_detail() {
            if (this.form.Children.integral_unitprice_detail.length > 1) {
                this.form.Children.integral_unitprice_detail.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        onExcel() {
            this.dialogVisible = true
        },
        beforeRemove(file, fileList) {
            this.fileList.pop()
        },
        uploadDetails(file) {
            this.fileList.push({
                name: file.name,
                url: file.type
            })
            let _this = this
            var reader = new FileReader();
            reader.readAsBinaryString(file);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var str = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
                console.log(str);
                //将整体数据分解成每一条，一条上传一次
                let newArr = []
                //1.将接受到数组便利
                //2.将栏目存到_this.integral_unitprice里并去重
                str.forEach((item, index) => {
                    if (newArr.indexOf(item['所属栏目']) == -1) {
                        newArr.push(item['所属栏目'])//根据这个数组判断是否重复
                        _this.integral_unitprice.push({
                            Integral_Unit_Price_SerialNumber: "",
                            Start_Date: "",
                            End_Date: "",
                            ShopColumn_Id: _this.Column(item['所属栏目']),
                            Children: {
                                integral_unitprice_detail: [],
                                integral_unitprice_storescope: []
                            }
                        })
                    }
                    //3.将商品等信息添加到对应栏目下的integral_unitprice_detail
                    _this.integral_unitprice.forEach((item1, index1) => {
                        if (_this.Column(item['所属栏目']) == item1.ShopColumn_Id) {
                            item1.Children.integral_unitprice_detail.push({
                                Sales_Unit_Price_Detail_SerialNumber: "",
                                Integral_Unit_Price_SerialNumber: '',
                                Article_SerialNumber: _this.Article(item['商品编号']),
                                Unit_Price: _this.Unit_Price(item['商品编号']),
                                Sales_Unit_Price: item['销售单价'],
                                Sign: item['有/无货货主'],
                                Distribute: parseInt(item['分配数量']),
                                Children: {
                                    integral_unitprice_stock: []
                                }
                            })
                        }
                    })
                })
            }
        },
        Automatic(item, Store_SerialNumber, Start_Date, End_Date, time, Integral_Unit_Price_Detail_SerialNumber) {
            //一天毫秒数
            let TimeDays = (1000 * 60) * 60 * 24
            if (+new Date(End_Date) <= +new Date(time)) {//若结算时间小于次日补货时间
                item.Children.integral_unitprice_stock.push({
                    Integral_Unit_Price_Stock_SerialNumber: "",
                    Integral_Unit_Price_Detail_SerialNumber: Integral_Unit_Price_Detail_SerialNumber,
                    Store_SerialNumber,
                    Start_Date: Start_Date,
                    End_Date: End_Date,
                    Distribute: parseInt(item.Distribute),
                    Stock_Remain: parseInt(item.Distribute),
                    Stock_Sell: 0
                })
            } else {//若结算时间大于次日补货时间
                item.Children.integral_unitprice_stock.push({
                    Integral_Unit_Price_Stock_SerialNumber: "",
                    Integral_Unit_Price_Detail_SerialNumber: Integral_Unit_Price_Detail_SerialNumber,
                    Store_SerialNumber,
                    Start_Date: Start_Date,
                    End_Date: this.formatTime(+new Date(time) - 1000),
                    Distribute: parseInt(item.Distribute),
                    Stock_Remain: parseInt(item.Distribute),
                    Stock_Sell: 0
                })
                this.Automatic(item, Store_SerialNumber, time, End_Date, this.formatTime(+new Date(time) + TimeDays), Integral_Unit_Price_Detail_SerialNumber)
            }
        },
        // 提交修改
        submitForm(formName) {
            let _this = this
            console.log(_this.form)
            if (_this.form.End_Date > _this.form.End_Date_Original) {
                //无货货主商品自动按照执行天数，生成货物
                let TimeDays = (1000 * 60) * 60 * 24
                //天数
                // let data = new Date(+new Date(_this.form.End_Date) - +new Date(_this.form.Start_Date)).getDate();
                //1.获取第一次补货时间
                let time = `${_this.form.End_Date_Original.substring(0, 10)} ${_this.always}`;
                if (+new Date(time) < +new Date(_this.form.End_Date)) {
                    time = _this.formatTime(+new Date(time) + TimeDays)
                }
                //2.判断结算时间是否小于第一次补货，如果小于等于生成1次库存，开始结束时间与主表相同
                //如果大于，第一次自动生成开始时间到补货时间，第二次自动生成判断剩余时间是否小于24小时，如果小于从补货时间开始，主表结束时间结束
                //如果大于补货时间开始到次日补货时间前1秒结束，第三次自动生成以此类推
                _this.form.Children.integral_unitprice_storescope.forEach(function (item1, index) {
                    _this.form.Children.integral_unitprice_detail.forEach(function (item, index) {
                        console.log(item)
                        if (item.Sign == "无货货主") {
                            _this.Automatic(item, item1.Store_SerialNumber, _this.form.End_Date_Original, _this.form.End_Date, time, item.Integral_Unit_Price_Detail_SerialNumber)
                        }
                    })
                })
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    // _this.delete(_this.form.Integral_Unit_Price_SerialNumber)
                    let integral_unitprice_stock = [];
                    _this.form.Children.integral_unitprice_detail.forEach(item => {
                        item.Children.integral_unitprice_stock.forEach(item1 => {
                            integral_unitprice_stock.push(item1)
                        })
                    })
                    _this.form.Children.integral_unitprice_detail.forEach(item => {
                        item.Children.integral_unitprice_stock = []
                        console.log(item.Children.integral_unitprice_stock);
                    })
                    const { add, modify } = _this.deal()
                    console.log(_this.form.Children.integral_unitprice_detail);
                    let data = {}
                    if (add == null) {
                        data = { Data: JSON.stringify({ Modify: { integral_unitprice: [modify] }, Add: { integral_unitprice_stock } }) }
                    } else {
                        data = {
                            Data: JSON.stringify(
                                {
                                    Modify: { integral_unitprice: [modify] },
                                    Add: { integral_unitprice: [add], integral_unitprice_stock }
                                }
                            )
                        }
                    }
                    console.log(JSON.parse(data.Data));
                    _this.loading = true
                    $.ajax({
                        url: DomainName + '/getEditAction?token=' + $.cookie("token"),
                        type: 'POST',
                        data,
                        success: function (res) {
                            console.log('点击提交',res)
                            if (res.Status === 'success') {
                                _this.$message.success("提交成功")
                                window.history.go(-1);
                            } else {
                                // _this.$message.error("提交失败，请稍后再试")
                                console.log(res)
                            }
                        },
                        error: function () {
                            _this.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            _this.loading = false
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        deal() {
            const add = deepClone(this.form)
            const modify = deepClone(this.form)
            let add_integral_unitprice_detail = [], modify_integral_unitprice_detail = []
            let add_integral_unitprice_storescope = [], modify_integral_unitprice_storescope = []
            let add_integral_unitprice_column = [], modify_integral_unitprice_column = []
            for (const i in modify.Children.integral_unitprice_detail) {
                const obj = modify.Children.integral_unitprice_detail[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_integral_unitprice_detail.push(obj)
                } else {
                    modify_integral_unitprice_detail.push(obj)
                }
            }
            for (const i in modify.Children.integral_unitprice_storescope) {
                const obj = modify.Children.integral_unitprice_storescope[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_integral_unitprice_storescope.push(obj)
                } else {
                    modify_integral_unitprice_storescope.push(obj)
                }
            }
            for (const i in modify.Children.integral_unitprice_column) {
                const obj = modify.Children.integral_unitprice_column[i];
                if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                    add_integral_unitprice_column.push(obj)
                    console.log(add_integral_unitprice_column)
                } else {
                    modify_integral_unitprice_column.push(obj)
                }
            }

            add.Children.integral_unitprice_detail = add_integral_unitprice_detail
            add.Children.integral_unitprice_storescope = add_integral_unitprice_storescope
            add.Children.integral_unitprice_column = add_integral_unitprice_column


            modify.Children.integral_unitprice_detail = modify_integral_unitprice_detail
            modify.Children.integral_unitprice_storescope = modify_integral_unitprice_storescope
            modify.Children.integral_unitprice_column = modify_integral_unitprice_column

            if (add_integral_unitprice_detail.length == 0 && add_integral_unitprice_storescope.length == 0 && add_integral_unitprice_column.length == 0) {
                return { add: null, modify };
            }
            return { add, modify };
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        Change_Unit_Price(index) {
            this.isDisabled = true
            let str = this.form.Children.integral_unitprice_detail[index].Article_SerialNumber
            for (let i = 0; i < this.shop.length; i++) {
                if (this.shop[i].Article_SerialNumber == str) {
                    this.form.Children.integral_unitprice_detail[index].Unit_Price = this.shop[i].Unit_Price
                }
            }
        },
        add_integral_scheme_storescope() {
            this.form.Children.integral_unitprice_storescope.push({     //销售价格单适用店铺
                Integral_Unit_Price_StoreScope_SerialNumber: "",
                Integral_Unit_Price_SerialNumber: '',
                Store_SerialNumber: '',
            })
        },
        remove_integral_scheme_storescope() {
            if (this.form.Children.integral_unitprice_storescope.length > 1) {
                this.form.Children.integral_unitprice_storescope.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        },
        add_integral_unitprice_detail() {
            this.form.Children.integral_unitprice_detail.push({     //销售价格单明细
                Sales_Unit_Price_Detail_SerialNumber: "",
                Integral_Unit_Price_SerialNumber: '',
                Article_SerialNumber: '',
                Unit_Price: '',
                Sales_Unit_Price: '',
            })
        },
        remove_integral_unitprice_detail() {
            if (this.form.Children.integral_unitprice_detail.length > 1) {
                this.form.Children.integral_unitprice_detail.pop()
            } else {
                this.$message({
                    message: '不能在删除了',
                    type: 'warning'
                })
            }
        }
    }
})